import { Context } from 'koa';
import { controller, get, post } from '../router/router';
import { jwt as jwtConf } from '../config/app';
import result from '../utils/result';
import jwt from 'jsonwebtoken';
import { Account, User, MenuAuth, accountList, userList, roleList, Role } from './userData';

@controller('/user')
export default class UserController {
    /**
     * 登录
     * @param ctx 
     * @param ctx.request.body.account
     * @param ctx.request.body.name
     * @param ctx.request.body.password
     */
    @post('/login')
    async login(ctx: Context) {
        const account = ctx.request.body.account;
        const loginName = ctx.request.body.loginName;
        const password = ctx.request.body.password;
        const res = new result(ctx);
        let accountItem: Account | undefined;
        let user: User | undefined;
        accountList.forEach(item => {
            if (item._id === account) return accountItem = item;

        });
        if (!accountItem) return res.error(400, '账号不存在');
        userList.forEach(userItem => {
            if (userItem.loginName === loginName && userItem.password === password) return user = userItem;
        });
        if (!user) return res.error(400, '用户名或密码错误');
        const token = jwt.sign({ _id: user._id, account_id: user.account_id, role_id: user.role_id }, jwtConf.SECRET, { expiresIn: jwtConf.EXPIRES });
        res.success({ token });
    }
    /**
     * 获取菜权限list
     * @param ctx 
     */
    @get('/getMenuAuth')
    async getMenuAuth(ctx: Context) {
        const res = new result(ctx);
        let menuAuth: MenuAuth | undefined;
        roleList.forEach(item => {
            if (item._id === ctx.user.role_id) return menuAuth = item.menuAuth;
        });
        if (menuAuth) {
            res.success(menuAuth);
        } else {
            res.error(403);
        }
    }
    /**
     * 获取用户列表
     * @param ctx 
     */
    @get('/getUserList')
    async getUserList(ctx: Context) {
        const res = new result(ctx);
        const users: User[] = [];
        userList.forEach(item => {
            if (item.account_id === ctx.user.account_id) {
                const userItem = JSON.parse(JSON.stringify(item));
                delete userItem.password;
                users.push(userItem);
            }
        });
        res.success(users);
    }
    /**
     * 获取角色列表
     * @param ctx 
     */
    @get('/getRoleList')
    async getRoleList(ctx: Context) {
        const res = new result(ctx);
        const roles: Role[] = [];
        roleList.forEach(item => {
            if (item.account_id === ctx.user.account_id) roles.push(item);
        });
        res.success(roles);
    }
}